<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="com.example.domain.Post" %>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑帖子</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #f8fafc 0%, #e0f2fe 100%);
            min-height: 100vh;
            color: #374151;
            padding: 20px;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            text-align: center;
            margin-bottom: 40px;
        }

        .header h1 {
            font-size: 32px;
            font-weight: bold;
            background: linear-gradient(135deg, #1f2937 0%, #3b82f6 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            margin-bottom: 8px;
        }

        .header p {
            color: #6b7280;
            font-size: 16px;
        }

        .edit-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            padding: 40px;
            border: 1px solid rgba(255, 255, 255, 0.2);
            transition: all 0.3s ease;
        }

        .edit-card:hover {
            box-shadow: 0 25px 50px rgba(0, 0, 0, 0.15);
            transform: translateY(-2px);
        }

        .form-group {
            margin-bottom: 24px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #374151;
            font-size: 16px;
        }

        .form-input {
            width: 100%;
            padding: 16px 20px;
            border: 2px solid #e5e7eb;
            border-radius: 12px;
            font-size: 16px;
            transition: all 0.3s ease;
            background: rgba(255, 255, 255, 0.8);
            font-family: inherit;
        }

        .form-input:focus {
            outline: none;
            border-color: #3b82f6;
            box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.1);
            background: white;
        }

        .form-textarea {
            min-height: 200px;
            resize: vertical;
            line-height: 1.6;
        }

        .button-group {
            display: flex;
            gap: 16px;
            justify-content: center;
            flex-wrap: wrap;
            margin-top: 32px;
        }

        .btn {
            padding: 14px 28px;
            border-radius: 25px;
            border: none;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            font-size: 16px;
            min-width: 140px;
            justify-content: center;
        }

        .btn-primary {
            background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);
            color: white;
            border: 2px solid transparent;
        }

        .btn-primary:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 25px rgba(59, 130, 246, 0.4);
        }

        .btn-secondary {
            background: transparent;
            border: 2px solid #6b7280;
            color: #6b7280;
        }

        .btn-secondary:hover {
            background: #6b7280;
            color: white;
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(107, 114, 128, 0.3);
        }

        .error-state {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            padding: 40px;
            text-align: center;
            border: 1px solid rgba(255, 255, 255, 0.2);
        }

        .error-state h3 {
            color: #ef4444;
            font-size: 24px;
            margin-bottom: 16px;
        }

        .error-state p {
            color: #6b7280;
            font-size: 16px;
            margin-bottom: 24px;
        }

        .error-message {
            background: linear-gradient(135deg, #fef2f2 0%, #fee2e2 100%);
            border: 2px solid #fecaca;
            border-radius: 12px;
            padding: 16px 20px;
            margin-top: 20px;
            color: #dc2626;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .success-message {
            background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);
            border: 2px solid #bbf7d0;
            border-radius: 12px;
            padding: 16px 20px;
            margin-top: 20px;
            color: #16a34a;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .back-link {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            color: #3b82f6;
            text-decoration: none;
            font-weight: 500;
            padding: 12px 20px;
            border-radius: 20px;
            transition: all 0.3s ease;
            border: 2px solid #3b82f6;
        }

        .back-link:hover {
            background: #3b82f6;
            color: white;
            transform: translateY(-2px);
        }

        .form-header {
            text-align: center;
            margin-bottom: 32px;
            padding-bottom: 20px;
            border-bottom: 2px solid #f3f4f6;
        }

        .form-header h2 {
            font-size: 24px;
            color: #1f2937;
            margin-bottom: 8px;
        }

        .form-header p {
            color: #6b7280;
            font-size: 14px;
        }

        .character-counter {
            text-align: right;
            font-size: 12px;
            color: #6b7280;
            margin-top: 4px;
        }

        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }

        .loading-spinner {
            width: 50px;
            height: 50px;
            border: 4px solid #f3f4f6;
            border-top: 4px solid #3b82f6;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .edit-card {
            animation: fadeIn 0.6s ease-out;
        }

        @media (max-width: 768px) {
            .container {
                padding: 16px;
            }

            .edit-card {
                padding: 24px;
                margin: 0 8px;
            }

            .header h1 {
                font-size: 28px;
            }

            .button-group {
                flex-direction: column;
                align-items: stretch;
            }

            .btn {
                width: 100%;
            }
        }

        @media (max-width: 480px) {
            .edit-card {
                padding: 20px;
            }

            .form-input {
                padding: 12px 16px;
                font-size: 14px;
            }

            .btn {
                padding: 12px 20px;
                font-size: 14px;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>✏️ 编辑帖子</h1>
        <p>修改您的帖子内容</p>
    </div>

    <%
        Post post = (Post) request.getAttribute("post");
        String errorMsg = (String) request.getAttribute("msg");

        if (post != null) {
    %>
    <div class="edit-card">
        <div class="form-header">
            <h2>编辑帖子</h2>
            <p>请修改您要更新的内容</p>
        </div>

        <form action="/post/update" method="post" onsubmit="showLoading()">
            <input type="hidden" name="id" value="<%= post.getId() %>">

            <div class="form-group">
                <label for="title">📝 标题</label>
                <input type="text"
                       id="title"
                       name="title"
                       value="<%= post.getTitle() %>"
                       required
                       class="form-input"
                       placeholder="请输入帖子标题..."
                       maxlength="200"
                       oninput="updateCharacterCount('title', 'title-counter', 200)">
                <div id="title-counter" class="character-counter">
                    <%= post.getTitle().length() %>/200
                </div>
            </div>

            <div class="form-group">
                <label for="content">📄 内容</label>
                <textarea id="content"
                          name="content"
                          required
                          class="form-input form-textarea"
                          placeholder="请输入帖子内容..."
                          maxlength="5000"
                          oninput="updateCharacterCount('content', 'content-counter', 5000)"><%= post.getContent() %></textarea>
                <div id="content-counter" class="character-counter">
                    <%= post.getContent().length() %>/5000
                </div>
            </div>

            <div class="button-group">
                <button type="submit" class="btn btn-primary">
                    <span>💾</span>
                    <span>更新帖子</span>
                </button>
                <a href="/user/profile" class="btn btn-secondary">
                    <span>❌</span>
                    <span>取消</span>
                </a>
            </div>
        </form>

        <% if (errorMsg != null && !errorMsg.trim().isEmpty()) { %>
        <div class="error-message">
            <span>⚠️</span>
            <span><%= errorMsg %></span>
        </div>
        <% } %>
    </div>

    <% } else { %>
    <div class="error-state">
        <div style="font-size: 48px; margin-bottom: 16px;">🚫</div>
        <h3>访问受限</h3>
        <p>帖子不存在或您没有权限编辑此帖子。</p>
        <a href="/user/profile" class="back-link">
            <span>🏠</span>
            <span>返回个人中心</span>
        </a>
    </div>
    <% } %>
</div>

<!-- 加载遮罩 -->
<div class="loading-overlay" id="loadingOverlay">
    <div class="loading-spinner"></div>
</div>

<script>
    // 字符计数功能
    function updateCharacterCount(inputId, counterId, maxLength) {
        const input = document.getElementById(inputId);
        const counter = document.getElementById(counterId);
        const currentLength = input.value.length;

        counter.textContent = currentLength + '/' + maxLength;

        // 根据字符数量改变颜色
        if (currentLength > maxLength * 0.9) {
            counter.style.color = '#ef4444';
        } else if (currentLength > maxLength * 0.7) {
            counter.style.color = '#f59e0b';
        } else {
            counter.style.color = '#6b7280';
        }
    }

    // 显示加载动画
    function showLoading() {
        document.getElementById('loadingOverlay').style.display = 'flex';
    }

    // 表单验证
    function validateForm() {
        const title = document.getElementById('title').value.trim();
        const content = document.getElementById('content').value.trim();

        if (title.length === 0) {
            showMessage('请输入标题', 'error');
            return false;
        }

        if (content.length === 0) {
            showMessage('请输入内容', 'error');
            return false;
        }

        if (title.length > 200) {
            showMessage('标题不能超过200个字符', 'error');
            return false;
        }

        if (content.length > 5000) {
            showMessage('内容不能超过5000个字符', 'error');
            return false;
        }

        return true;
    }

    // 显示消息提示
    function showMessage(message, type) {
        const messageDiv = document.createElement('div');
        messageDiv.textContent = message;
        messageDiv.className = type === 'error' ? 'error-message' : 'success-message';
        messageDiv.style.position = 'fixed';
        messageDiv.style.top = '20px';
        messageDiv.style.right = '20px';
        messageDiv.style.zIndex = '1001';
        messageDiv.style.maxWidth = '300px';

        document.body.appendChild(messageDiv);

        setTimeout(() => {
            if (messageDiv.parentNode) {
                document.body.removeChild(messageDiv);
            }
        }, 3000);
    }

    // 自动保存草稿功能
    let autoSaveTimer;
    function autoSave() {
        clearTimeout(autoSaveTimer);
        autoSaveTimer = setTimeout(() => {
            const title = document.getElementById('title').value;
            const content = document.getElementById('content').value;

            // 保存到本地存储
            localStorage.setItem('editPost_draft_title', title);
            localStorage.setItem('editPost_draft_content', content);

            console.log('草稿已自动保存');
        }, 2000);
    }

    // 页面加载时恢复草稿
    window.addEventListener('load', function() {
        const savedTitle = localStorage.getItem('editPost_draft_title');
        const savedContent = localStorage.getItem('editPost_draft_content');

        if (savedTitle && savedTitle !== document.getElementById('title').value) {
            if (confirm('检测到未保存的草稿，是否恢复？')) {
                document.getElementById('title').value = savedTitle;
                updateCharacterCount('title', 'title-counter', 200);
            }
        }

        if (savedContent && savedContent !== document.getElementById('content').value) {
            if (confirm('检测到未保存的内容草稿，是否恢复？')) {
                document.getElementById('content').value = savedContent;
                updateCharacterCount('content', 'content-counter', 5000);
            }
        }
    });

    // 监听输入变化，触发自动保存
    document.getElementById('title').addEventListener('input', autoSave);
    document.getElementById('content').addEventListener('input', autoSave);

    // 表单提交时清除草稿
    document.querySelector('form').addEventListener('submit', function() {
        localStorage.removeItem('editPost_draft_title');
        localStorage.removeItem('editPost_draft_content');
    });

    // 页面离开前提醒保存
    window.addEventListener('beforeunload', function(e) {
        const title = document.getElementById('title');
        const content = document.getElementById('content');

        if (title && content) {
            const originalTitle = '<%= post != null ? post.getTitle() : "" %>';
            const originalContent = '<%= post != null ? post.getContent().replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "\\r") : "" %>';

            if (title.value !== originalTitle || content.value !== originalContent) {
                e.preventDefault();
                e.returnValue = '您有未保存的更改，确定要离开吗？';
                return e.returnValue;
            }
        }
    });
</script>
</body>
</html>
